package com.joekai.view_demo.foldList;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.ViewCompat;
import androidx.customview.widget.ViewDragHelper;

import com.joekai.view_demo.R;

/**
 * @author joekai
 */
public class FoldListView extends FrameLayout {

    private ViewDragHelper mDragHelper;
    private View mTopView;
    private View mSlideView;
    private int mTopHeight = 0;
    // 菜单是否打开
    private boolean mIsOpenMenu = false;

    public FoldListView(@NonNull Context context) {
        this(context, null);
    }

    public FoldListView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FoldListView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public FoldListView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initAttr(context, attrs);
        init();
    }

    private void initAttr(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.FoldListView);
        ta.recycle();
    }

    private void init() {
        mDragHelper = ViewDragHelper.create(this, mViewDragHelperCallback);
    }

    private ViewDragHelper.Callback mViewDragHelperCallback = new ViewDragHelper.Callback() {
        @Override
        public boolean tryCaptureView(@NonNull View child, int pointerId) {
            //指定该子View是否可以拖动
            return mSlideView == child;
        }

        @Override
        public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
            //垂直拖动移动的位置
            if (top > mTopHeight) {
                top = mTopHeight;
            }
            if (top < 0) {
                top = 0;
            }
            return top;
        }

        @Override
        public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) {
            super.onViewReleased(releasedChild, xvel, yvel);
            if (releasedChild == mSlideView) {
                if (mSlideView.getTop() > mTopHeight / 2) {
                    //打开
                    Log.e("---TAG打开", "/" + mTopHeight + "/" + mSlideView.getTop());
                    mDragHelper.settleCapturedViewAt(0, mTopHeight);
                    //丝滑的滑动view到（0，0）位置
                    mIsOpenMenu = true;
                } else {
                    //关闭
                    Log.e("---TAG关闭", "/" + mTopHeight + "/" + mSlideView.getTop());
                    mDragHelper.settleCapturedViewAt(0, 0);
                    mIsOpenMenu = false;
                    //丝滑的滑动view到（0，0）位置

                }
                invalidate();
            }

        }
    };

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            mTopHeight = mTopView.getMeasuredHeight();
        }

    }

    /**
     * 滚动响应
     */
    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mDragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(FoldListView.this);
        }
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int viewCount = getChildCount();
        if (viewCount != 2) {
            throw new RuntimeException("需要两个布局");
        }
        mTopView = getChildAt(0);
        mSlideView = getChildAt(1);
    }

    // 现象就是ListView可以滑动，但是菜单滑动没有效果了
    private float mDownY;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // 菜单打开要拦截
        if (mIsOpenMenu) {
            return true;
        }
        // 向下滑动拦截，不要给ListView做处理
        // 谁拦截谁 父View拦截子View ，但是子 View 可以调这个方法
        // requestDisallowInterceptTouchEvent 请求父View不要拦截，改变的其实就是 mGroupFlags 的值
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDownY = ev.getY();
                // 让 DragHelper 拿一个完整的事件
                mDragHelper.processTouchEvent(ev);
                break;
            case MotionEvent.ACTION_MOVE:
                float moveY = ev.getY();
                if ((moveY - mDownY) > 0 && !canChildScrollUp()) {
                    // 向下滑动 && 滚动到了顶部，拦截不让ListView做处理
                    return true;
                }
                break;
            default:
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    /**
     * @return Whether it is possible for the child view of this layout to
     * scroll up. Override this if the child view is a custom view.
     * 判断View是否滚动到了最顶部,还能不能向上滚
     */
    public boolean canChildScrollUp() {
        if (android.os.Build.VERSION.SDK_INT < 14) {
            if (mSlideView instanceof AbsListView) {
                final AbsListView absListView = (AbsListView) mSlideView;
                return absListView.getChildCount() > 0
                        && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
                        .getTop() < absListView.getPaddingTop());
            } else {
                return mSlideView.canScrollVertically(-1) || mSlideView.getScrollY() > 0;
            }
        } else {
            return mSlideView.canScrollVertically(-1);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mDragHelper.processTouchEvent(event);
        return true;
    }

}
